﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Talento21.Pages.Empresa
{
    public partial class Crear : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            if (e.Exception == null)
            {
                Master.AgregarMensaje("Se ha creado una nueva Empresa satisfactoriamente");
                e.KeepInInsertMode = true;
                TextBox rutTextBox = (TextBox)this.FormView1.FindControl("Emp_rutTextBox");
                Session["RutEmpGuardad"] = int.Parse(rutTextBox.Text);

                Server.Transfer("NuevoUsuarioAdmin.aspx");
            }

        }

        protected void EmpresaDataSource_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
        {

        }

        protected void ValidarRut(object sender, ServerValidateEventArgs arguments)
        {
            var dvIngresado = arguments.Value;
            arguments.IsValid = false;

            var rut = ((TextBox)this.FormView1.FindControl("Emp_rutTextBox")).Text;

            var factor = 2;
            var suma = 0;
            var dv = string.Empty;


            for (int i = (rut.Length - 1); i >= 0; i--)
            {
                factor = factor > 7 ? 2 : factor;
                suma += int.Parse(rut[i].ToString()) * factor++;
            }
            dv = (11 - (suma % 11)).ToString();
            if (dv == "11")
            {
                dv = "0";
            }
            else if (dv == "10")
            {
                dv = "k";
            }

            arguments.IsValid = dv == dvIngresado.ToUpper();


        }
    }
}